package com.mzw.project.bizmq;


import com.mzw.project.model.entity.VoucherOrder;
import com.mzw.project.service.VoucherOrderService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * @author L1nAn
 */
@Component
@Slf4j
public class BiMessageFailConsumer {

    @Resource
    private VoucherOrderService voucherOrderService;

    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.API_DEAD_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        String[] splits = message.split(",");
        long userId = Long.parseLong(splits[0]);
        long orderId = Long.parseLong(splits[1]);
        long voucherId = Long.parseLong(splits[2]);
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        // 创建订单
        try {
            voucherOrderService.createVoucherOrder(voucherOrder);
            // 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.info("创建订单失败", e);
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
